const express = require('express');
const router = express.Router();
// const redisClient = require('../db/redis');
const { getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
  getTag,
  getComments,
  addBrowseNum,
  searchByTitle
} = require('../controller/blog');
const {SuccessModel, ErrorModel} = require('../model/resModel');
const loginCheck = require('../middleWare/loginCheck');
const rootCheck = require('../middleWare/rootCheck');

router.get('/list', (req, res, next) => {
  // 获取博客列表
  let author = req.query.author || '';
  const keyword = req.query.keyword || '';
  const tagName = req.query.tagName || '';
  const result = getList(author, keyword, tagName);
  return result.then(listData => {
    res.json(new SuccessModel(listData));
  }).catch(err => {
    res.json(new ErrorModel('获取博客列表失败'))
  })
});



// router.get('/getListByTagName', (req, res, next) => {
//   let tagName = req.query.tagName;
//   const result = getTag(tagName);
//   console.log('tagName',tagName);
//   result.then(tagData => {
//     res.json(new SuccessModel(tagData));
//   }).catch(err => {
//     console.log(new Error('获取tags失败'));
//   })
//
// });

router.get('/detail', (req, res, next) => {
  const result = getDetail(req.query.id);
  return result.then(detailData => {
    res.json(new SuccessModel(detailData));
  })
});

// 更新博客访问量（+1）
router.get('/addBrowseNum', (req, res, next) => {
  const blogId = req.query.blogId;
  const result = addBrowseNum(blogId);
  return result.then(msg => {
    res.json('msg');
  })
});

router.post('/new', loginCheck, rootCheck, (req, res, next) => {
  req.body.author = req.session.username;
  // console.log(req.body.author);
  const result = newBlog(req.body);
  return result.then(data => {
    console.log('newBlog-success', data);
    res.json(new SuccessModel(data))
  }).catch(err => {
    console.log('创建博客失败');
    res.json(new ErrorModel('创建博客失败'));
  })
});

router.post('/update', loginCheck, rootCheck, (req, res, next) => {
  const result = updateBlog(req.query.id, req.body);
  return result.then(val => {
    if (val) {
      res.json(
        new SuccessModel()
      )
    } else {
      res.json(
        new ErrorModel('更新博客失败')
      )
    }
  })
});

router.post('/del', loginCheck, rootCheck, (req, res, next) => {
  const author = req.session.username;
  const result = delBlog(Number(req.body.blogId), author);
  return result.then(val => {
    if (val) {
      res.json(new SuccessModel());
    } else {
      res.json(new ErrorModel('删除博客失败'));
      return new ErrorModel('删除博客失败')
    }
  })
});

router.get('/search', async (req, res, next)=> {
  const title = req.query.title;
  try {
    const result = await searchByTitle(title);
    res.json(new SuccessModel(result));
  } catch (err) {
    res.json(new ErrorModel(err));
  }
});

module.exports = router;

